package com.lht.designPattern.nullObject;

public class NullObjectPattern {

    public static void main(String[] args) {
        //--------------平时我们正常使用得时候--------
        DriverFactory factory = new DriverFactory();
        Driver driver = factory.normal("cuowude");//传一个错误类型进去
        if (null != driver) {
            driver.drive();
        }


        ////---------空对象模式----------------
        DriverFactory nullObjectFactory=new DriverFactory();
        Driver nullObjectDriver=factory.getNullObject("error");
        nullObjectDriver.drive();//这里不需要做任何空指针判断，因为对象一定不会为空

    }

}

interface Driver {

    String PERSION_TYPE = "persion";
    String DOG_TYPE = "dog";

    void drive();
}

class PersonDriver implements Driver {

    @Override
    public void drive() {
        System.out.println("Persion drive");
    }
}

class DogDriver implements Driver {

    @Override
    public void drive() {
        System.out.println("Dog drive");
    }
}

class NullDriver implements Driver {

    @Override
    public void drive() {
        System.out.println("Null drive");
    }
}

class DriverFactory {

    public Driver normal(String driverType) {
        switch (driverType) {
            case Driver.PERSION_TYPE:
                return new PersonDriver();
            case Driver.DOG_TYPE:
                return new DogDriver();
        }
        return null;
    }

    public Driver getNullObject(String driverType) {
        switch (driverType) {
            case Driver.PERSION_TYPE:
                return new PersonDriver();
            case Driver.DOG_TYPE:
                return new DogDriver();
        }
        return new NullDriver();
    }
}

